// 把一个整数num,转换成指定长度byteLength的字节数组，（按大端存储）
// 1 转换成 指定 长度为2 的字节数组: 1 => [0,1]. 即[0x00,0x01]
// 255 转换成 指定 长度为4 的字节数组: 255 => [0,0,0,255]. 即[0x00,0x00,0x00,0xFF]
function toBytes(num, byteLength) {
    const bytes = new Array(byteLength).fill(0);
    for (let i = byteLength - 1; i >= 0; i--) {
        bytes[i] = num & 0xFF;
        num >>= 8;
    }
    return bytes;
}
// [aa,ff,1] => [0xAA,0xFF,0x01]
function formatHex(arr) {
    return arr.map(n => '0x' + n.toString(16).padStart(2, '0').toUpperCase());
}


// [0x11,0x22,0x33].decimal => 1122867 (0x112233)
// [0x11,0x22,0x33].slice(0,1).decimal => 17 (0x11)
Object.defineProperties(Array.prototype, {
    decimal: {
        get: function () {
            return this.reduce((acc, byte) => (acc << 8) | byte, 0);
        },
    },
});

///console.log(formatDate()); // 示例输出: "2023-08-25 14:05:23.456"
export function formatDate() {
    const now = new Date();
    
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    const milliseconds = String(now.getMilliseconds()).padStart(3, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${milliseconds}`;
}


///弹出下拉框
function showDropdown(father, drop_el, direction = 'bottom', width = 0) {
    const rect = father.getBoundingClientRect();
    const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;

    const absTop = rect.top + scrollTop;
    const absLeft = rect.left + scrollLeft;
    const w = (width === 0 || width === null) ? rect.width : width;

    drop_el.style.position = 'absolute';
    drop_el.style.width = `${w}px`;

    if (direction === 'bottom') {
        drop_el.style.top = `${absTop + rect.height}px`;
        drop_el.style.left = `${absLeft}px`;
    } else if (direction === 'right') {
        drop_el.style.top = `${absTop}px`;
        drop_el.style.left = `${absLeft + rect.width}px`;
    } else if (direction === 'left') {
        drop_el.style.top = `${absTop}px`;
        drop_el.style.left = `${absLeft - drop_el.offsetWidth}px`;
    } else if (direction === 'top') {
        drop_el.style.top = `${absTop - drop_el.offsetHeight}px`;
        drop_el.style.left = `${absLeft}px`;
    } else if (direction === 'bottom_left') {
        drop_el.style.top = `${absTop + rect.height}px`;
        drop_el.style.right = `${window.innerWidth - rect.right}px`;
    }
    // 切换显示状态
    drop_el.style.display = (drop_el.style.display === 'block') ? 'none' : 'block';
}

///添加自定义的公用html模块
// loadCustom({ selector: '[delay-horn]', defaultPath: 'horn_button.html' });
function loadCustom({ selector, defaultPath, callback }) {
    const container = document.querySelector(selector);
    if (!container) {
        console.error(`No container found for selector: ${selector}`);
        return;
    }

    const path = container.getAttribute(selector.replace(/[\[\]]/g, '')) || defaultPath;

    fetch(path)
        .then(response => response.text())
        .then(data => {
            container.innerHTML = data;

            // 执行其中的 script
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = data;
            const scripts = tempDiv.querySelectorAll('script');

            scripts.forEach(oldScript => {
                const newScript = document.createElement('script');

                // 检查是不是 module（推荐你写成 script 标签时标注 type="module"）
                if (oldScript.type === 'module') {
                    newScript.type = 'module';
                }

                if (oldScript.src) {
                    newScript.src = oldScript.src;
                } else {
                    newScript.textContent = oldScript.textContent;
                }

                // 将脚本插入到 body 中（或 container 中）
                document.body.appendChild(newScript);
            });

            if (typeof callback === 'function') {
                callback(container);
            }
        })
        .catch(err => {
            console.error(`Failed to load custom from ${path}:`, err);
        });
}
export { formatHex, loadCustom, showDropdown, toBytes };

